package com.ming.common.init;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.Tailer;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.query.LambdaQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Component
public class LogInit {

    private static final Logger LOG = LoggerFactory.getLogger(LogInit.class);

    @Resource
    private SQLManager sqlManager;

    @PostConstruct
    public void init(){
        String logPath = "logs\\ivy.log";
        ThreadUtil.execAsync(()->{
            // 清空日志文件
            clearLogFile(logPath);
            // 监听System.out.println输出的内容并追加到日志文件
            systemLogTailer(logPath);
            // 启动Tailer监听日志文件变化
            startLogTailer(logPath);
        });
    }

    private static void clearLogFile(String filePath) {
        try (FileWriter fileWriter = new FileWriter(filePath, false)) {
            // 清空文件内容
            fileWriter.write("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void systemLogTailer(String filePath) {
        // 保存原始的 System.out
        PrintStream originalSystemOut = System.out;
        // 创建一个自定义的 PrintStream
        PrintStream customPrintStream = new PrintStream(originalSystemOut) {
            @Override
            public void println(String x) {
                // 将输出内容写入日志
                try (FileWriter fileWriter = new FileWriter(filePath, true)) {
                    fileWriter.write(x+System.lineSeparator());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                // 再将内容输出到原始的 System.out
                super.println(x);
            }
        };
        // 重定向 System.out 到自定义的 PrintStream
        System.setOut(customPrintStream);

        // 恢复原始的 System.out
        // System.setOut(originalSystemOut);
    }

    private static List<String> list;
    private static boolean flag;
    public static Map<String,List<String>> logMap = new HashMap<>();
    private static int length = (System.currentTimeMillis()+"").length();
    public static String startKey = "-start-source-code-test";
    public static String endKey = "-end-source-code-test";

    public static LogInfo getLogInfo(){
        long ms = System.currentTimeMillis();
        LogInfo logInfo = new LogInfo(ms + LogInit.startKey, ms + LogInit.endKey);
        LOG.info(logInfo.getStartKey());
        return logInfo;
    }

    private static void startLogTailer(String filePath) {
        File logFile = new File(filePath);
        Tailer tailer = new Tailer(logFile, (line) -> {
            boolean startWith = line.endsWith(startKey);
            boolean endsWith = line.endsWith(endKey);
            if(flag && !endsWith){
                list.add(line);
            }
            if(startWith){
                list = new ArrayList<>();
                flag = true;
            }
            if(endsWith){
                flag = false;
                logMap.put(line.substring(line.length() - endKey.length() - length),list);
            }
        }, 0);
        tailer.start();
    }

    public static Map<String,Object> getResultVal(Object returnVal,LogInfo logInfo) {
        System.out.println("结果数据：");
        System.out.println(JSON.toJSONString(returnVal,true));
        LOG.info(logInfo.getEndKey());
        String endKey = logInfo.getEndKey();
        List<String> list = LogInit.logMap.get(endKey);
        while (list == null || list.isEmpty()) {
            list = LogInit.logMap.get(endKey);// 等待list不为空
            ThreadUtil.sleep(100);
        }
        LogInit.logMap.remove(endKey);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("returnVal", returnVal);
        resultMap.put("logStr", String.join(System.lineSeparator(),list));
        return resultMap;
    }
}
